package com.moon.game.server;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

/**
 * 
 * Session检查器
 * 
 * 
 */
public class CheckSessionTask {

	private static Logger logger = Logger.getLogger(CheckSessionTask.class);
	private Timer timer = new Timer();

	public CheckSessionTask() {
	}

	/**
	 * 计时器启动
	 * 
	 * 5分钟检查次
	 */
	public void start() {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.set(GregorianCalendar.HOUR_OF_DAY, 00);
		calendar.set(GregorianCalendar.MINUTE, 00);
		calendar.set(GregorianCalendar.SECOND, 01);
		int period = 1 * 60 * 1000;
		timer.schedule(new TimerTask() {
			public void run() {
				checkSession();
			}
		}, calendar.getTime(), period);

	}

	private void checkSession() {
		long start = System.currentTimeMillis();
		ConcurrentHashMap<String, DataSession> sessions = NetServer.getDataSessions();
		List<String> ids = new ArrayList<String>();
		for (Map.Entry<String, DataSession> sessionEntry : sessions.entrySet()) {
			String key = sessionEntry.getKey();
			DataSession sesison = sessionEntry.getValue();
			if (System.currentTimeMillis() - sesison.getCreateTime() > 1000 * 60 * 5) {
				ids.add(key);
			}
		}
		// 大于1分钟从队列移除
		for (String key : ids) {
			sessions.remove(key);
		}
		long end = System.currentTimeMillis();
		logger.warn("check session use time:" + (end - start));
	}

}
